package linkedlist;

import java.util.Iterator;

public class DoubleCircularLinkedListSentinel implements Iterable<Integer> {
    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            Node pointer = sentinel.next;

            @Override
            public boolean hasNext() {
                return pointer != sentinel;
            }

            @Override
            public Integer next() {
                int value = pointer.value;
                pointer = pointer.next;
                return value;
            }
        };
    }

    private static class Node {
        Node prev;
        int value;
        Node next;

        public Node(Node prev, int value, Node next) {
            this.prev = prev;
            this.value = value;
            this.next = next;
        }
    }

    private Node sentinel = new Node(null, 666, null);

    public DoubleCircularLinkedListSentinel() {
        sentinel.prev = sentinel;
        sentinel.next = sentinel;
    }

    /**
     * 向双向循环链表的首位添加节点
     *
     * @param value 添加值
     */
    public void addFist(int value) {
        Node prev = sentinel;
        Node next = sentinel.next;
        Node added = new Node(prev, value, next);
        prev.next = added;
        next.prev = added;
    }

    /**
     * 向双向循环链表末尾添加节点
     *
     * @param value 插入值
     */
    public void addLast(int value) {
        Node prev = sentinel.prev;
        Node next = sentinel;
        Node added = new Node(prev, value, sentinel);
        prev.next = added;
        next.prev = added;
    }

    /**
     * 删除循环链表第一个元素
     */
    public void removeFirst() {
        Node prev = sentinel;
        Node removed = sentinel.next;
        if (removed == sentinel) {
            throw new IllegalArgumentException("非法操作！");
        }
        Node next = removed.next;
        prev.next = next;
        next.prev = prev;
    }

    /**
     * 删除循环链表最后一个元素
     */
    public void removeLast() {
        Node next = sentinel;
        Node removed = sentinel.prev;
        if (removed == sentinel) {
            throw new IllegalArgumentException("非法操作！");
        }
        Node prev = removed.prev;
        next.prev = prev;
        prev.next = next;
    }

    /**
     * 通过值删除节点
     *
     * @param value 目标值
     */
    public void removeByValue(int value) {
        Node removed = findNodeByValue(value);
        if (removed == null) {
            throw new IllegalArgumentException("该值不存在节点");
        }
        Node prev = removed.prev;
        Node next = removed.next;
        prev.next = next;
        next.prev = prev;
    }

    /**
     * 通过值查找节点
     *
     * @param value 目标值
     * @return 返回节点，没找到则返回空
     */
    private Node findNodeByValue(int value) {
        for (Node pointer = sentinel.next; pointer != sentinel; pointer = pointer.next) {
            if (pointer.value == sentinel.value) {
                return pointer;
            }
        }
        return null;
    }
}
